package com.wsc.wscbirthdaykeeper.utils.comparators;

import java.util.Calendar;
import java.util.Comparator;
import java.util.GregorianCalendar;

import com.wsc.wscbirthdaykeeper.model.entity.Person;

public class PersonComparator implements Comparator<Person> {
	private Calendar lastDayInYear;
	private Calendar currentDay;

	public PersonComparator() {
		lastDayInYear = GregorianCalendar.getInstance();
		lastDayInYear.set(Calendar.HOUR, 0);
		lastDayInYear.set(Calendar.MINUTE, 0);
		lastDayInYear.set(Calendar.SECOND, 0);
		lastDayInYear.set(Calendar.MILLISECOND, 0);
		lastDayInYear.set(Calendar.HOUR_OF_DAY, 0);
		lastDayInYear.set(Calendar.MONTH, 11);
		lastDayInYear.set(Calendar.DATE, 31);

		currentDay = GregorianCalendar.getInstance();
	}

	@Override
	public int compare(Person item1, Person item2) {
		Calendar c1 = GregorianCalendar.getInstance();
		c1.setTime(item1.getDate());
		int dayInYear1 = c1.get(Calendar.DAY_OF_YEAR);

		if (dayInYear1 < currentDay.get(Calendar.DAY_OF_YEAR)) {
			dayInYear1 = dayInYear1 + lastDayInYear.get(Calendar.DAY_OF_YEAR) - currentDay.get(Calendar.DAY_OF_YEAR);
		} else {
			dayInYear1 = dayInYear1 - currentDay.get(Calendar.DAY_OF_YEAR);
		}

		Calendar c2 = GregorianCalendar.getInstance();
		c2.setTime(item2.getDate());
		int dayInYear2 = c2.get(Calendar.DAY_OF_YEAR);
		if (dayInYear2 < currentDay.get(Calendar.DAY_OF_YEAR)) {
			dayInYear2 = dayInYear2 + lastDayInYear.get(Calendar.DAY_OF_YEAR) - currentDay.get(Calendar.DAY_OF_YEAR);
		} else {
			dayInYear2 = dayInYear2 - currentDay.get(Calendar.DAY_OF_YEAR);
		}

		if (dayInYear1 > dayInYear2) {
			return 1;
		}
		if (dayInYear1 == dayInYear2) {
			return 0;
		}
		return -1;
	}
}
